<template>
  <section>
    <!--  搜索  -->
    <div class="user-search">
      <el-form :inline="true" :model="customer" size="small">
        <el-form-item label="客户姓名">
          <el-input v-model="customer.name" placeholder="客户姓名" />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="filter.date" type="daterange" align="right" unlink-panels range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="type === 'private'" label="联系电话">
          <el-input v-model="customer.mobile" placeholder="联系电话" />
        </el-form-item>
        <el-form-item v-if="type === 'private'" label="跟进状态">
          <el-select v-model="followStatus" multiple collapse-tags placeholder="默认全部">
            <el-option v-for="item in followStatusArray" :key="item.status" :label="item.value" :value="item.status" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="type === 'public'">
          <el-checkbox v-model="customer.showClose" 
          label="显示关闭客户" border 
          @change="init" />
        </el-form-item>
        <el-form-item v-if="type === 'public'">
          <el-checkbox v-model="customer.notAssign" 
          label="仅显示未指派" border 
          @change="init" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="init">查询</el-button>
          <el-button v-permission="['ADMIN', 'CUSTOMER_ALL', 'CUSTOMER_IMPORT']" 
            v-if="type === 'public'" 
            type="success"
            icon="el-icon-upload" 
            @click="uploadDialog.visible = true">导入客户</el-button>
          <!-- <el-button v-if="type === 'public' && selections.length > 0" type="danger">批量关闭</el-button> -->
        </el-form-item>
      </el-form>
    </div>

    <div class="user-operator">
      <el-button v-permission="['ADMIN', 'CUSTOMER_ALL', 'CUSTOMER_ADD']" 
        type="primary"
        icon="el-icon-plus"
        size="small"
        @click="addCustomer()">新增客户</el-button>
      <el-button v-permission="['ADMIN', 'CUSTOMER_ALL', 'CUSTOMER_ASSIGN']" 
        v-if="type === 'public'"
        :disabled="selections.length == 0" 
        icon="el-icon-edit-outline" 
        type="primary"
        size="small"
        @click="batchFollow">分配跟进</el-button>
    </div>

    <!--列表-->
    <el-table v-loading="loading" :data="data" highlight-current-row style="width: 100%;" @selection-change="selectionChange">
      <el-table-column v-if="type ==='public'" type="selection"/>
      <el-table-column type="index" label="序号" width="50">
        <template slot-scope="scope">
          <span>{{ scope.$index+(page - 1) * size + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学员姓名" width="80">
        <template slot-scope="scope">
          <router-link v-if="type==='private'" :to="`/customer/detail/${scope.row.merchantCustomerId}/1`">
            <el-button type="text">{{ scope.row.studentName }}</el-button>
          </router-link>
          <router-link v-if="type==='public'" :to="`/customer/detail/${scope.row.merchantCustomerId}/0`">
            <el-button type="text">{{ scope.row.studentName }}</el-button>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column prop="mobile" label="联系方式" min-width="110">
        <template slot-scope="scope">
          {{ scope.row.mobile || '-' }}
        </template>
      </el-table-column>
      <el-table-column v-if="type == 'private'" prop="address" label="家庭地址" min-width="120" />
      <el-table-column prop="name" label="客户姓名" min-width="80">
        <template slot-scope="scope">
          {{ scope.row.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="relation" label="客户关系" min-width="80">
        <template slot-scope="scope">
          {{ scope.row.relation || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="school" label="所在学校" min-width="140">
        <template slot-scope="scope">
          {{ scope.row.school || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="gradeName" label="所在年级" min-width="80" />
      <el-table-column prop="sourceName" label="来源" width="90"/>
      <el-table-column v-if="type === 'public'" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.state === 1" type="success">{{ scope.row.stateTxt }}</el-tag>
          <el-tag v-else-if="scope.row.state === 2" type="info">{{ scope.row.stateTxt }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="intention" v-if="type === 'private'" sortable label="意向" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.intention === 4" type="warning">{{ scope.row.intentionTxt }}</el-tag>
          <el-tag v-else-if="scope.row.intention === 3" type="success">{{ scope.row.intentionTxt }}</el-tag>
          <el-tag v-else type="info">{{ scope.row.intentionTxt }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="creator" label="建档人">
        <template slot-scope="scope">
          {{ scope.row.creator || '-' }}
        </template>
      </el-table-column>
      <el-table-column v-if="type === 'private'" label="客户需求" :show-overflow-tooltip="true"  min-width="150">
        <template slot-scope="scope">
          {{ scope.row.requirement && scope.row.requirement.slice(0, 20) }}
        </template>
      </el-table-column>
      <el-table-column v-if="type === 'private'" label="下次回访时间" width="110">
        <template slot-scope="scope">
          {{ scope.row.nextFollowTime | formatDate }}
        </template>
      </el-table-column>
      <el-table-column v-if="type === 'public'" prop="followOpName" label="跟进人">
        <template slot-scope="scope">
          {{ scope.row.followOpName || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="followTimes" label="跟进次数" />
      <el-table-column prop="followStatusName" sortable label="状态" />
      <el-table-column label="录入时间" sortable width="100">
        <template slot-scope="scope">
          {{ scope.row.createdAt | formatDate('yyyy-MM-dd') }}
        </template>
      </el-table-column>
      <el-table-column label="操作" :width="style" fixed="right">
        <template slot-scope="scope">
          <!--客户公池操作-->
          <span v-if="type === 'public'">
            <el-button type="text" :disabled="scope.row.followOpId != null && scope.row.followId != 0"
              @click="addCustomer(scope.row.merchantCustomerId)">编辑</el-button>
            <em class="block-col"/>
            <span v-if="scope.row.state === 1">
              <el-button type="text" v-permission="['ADMIN', 'CUSTOMER_ALL', 'CUSTOMER_TRASH']"
                @click="closeCustomer(scope.row.merchantCustomerId)">关闭</el-button>
            </span>
            <span v-else>
              <el-button type="text" @click="reopenCustomer(scope.row.merchantCustomerId)">打开</el-button>
            </span>
          </span>

          <!--客户私池操作-->
          <span v-else-if="type === 'private'">
            <el-button type="text" @click="updateOpportunity(scope.row.merchantCustomerId, scope.row.studentName, scope.row.opportunityId)">跟进</el-button>
            <em class="block-col"/>
            <el-dropdown>
              <span class="el-dropdown-link">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-button type="text" @click="listenClass(scope.row)">试听</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <router-link v-if="scope.row.followStatus < 9" :to="{path: '/customer/sign', query: {merchantCustomerId: scope.row.merchantCustomerId}}">
                    <el-button type="text">报名</el-button>
                  </router-link>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </span>
        </template>
      </el-table-column>
    </el-table>

    <!--分页组件-->
    <div class="pg-wrapper">
      <el-pagination
        :total="total"
        layout="total, prev, pager, next, sizes, jumper"
        @size-change="sizeChange"
        @current-change="pageChange"/>
    </div>

    <form-dialog 
      :visible="customerDialog.visible"
      :title="customerDialog.title"
      :merchant-customer-id="customerDialog.id" 
      :is-private="customerDialog.isPrivate" 
      :type="customerDialog.type"
      @close="closeFormDialog" />

    <el-drawer
      title="客户跟进"
      :visible.sync="followDialog.visible"
      direction="rtl"
      size="35%">
      
      <div class="follow-source">
        <follow-form 
          :id="followDialog.id"
          :customer-name="followDialog.customerName"
          :opportunity-id="followDialog.opportunityId" 
          :operators="operators"
          :key="followDialog.id"
          @success="followSuccess"/>

        <el-tabs v-model="activeName">
          
          <el-tab-pane label="跟进记录" name="followTab">
            <el-table :data="followLogs" :show-header=false>
              <el-table-column prop="createTime" label="跟进时间" width="180"/>
              <el-table-column prop="followStatusName" label="跟进状态"/>
              <el-table-column prop="content" label="跟进记录"/>
            </el-table>

            <el-button class="more" type="text" @click="onMore(followDialog.id)">查看更多</el-button>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>

    <el-dialog :visible.sync="batchFollowVisible" title="分配课程顾问" width="600px">
      <el-form :inline="true">
        <el-form-item label="选择课程顾问">
          <el-select v-model="batchFollowOperatorId" placeholder="选择课程顾问">
            <el-option v-for="o in operators" :label="o.label" :value="o.value" :key="o.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button :loading="batchFollowLoading" type="primary" @click="batchFollowSubmit">确定</el-button>
      </div>
    </el-dialog>

    <listen-dialog 
      :visible="listenDialog.visible"
      :listen-id="listenDialog.listenId"
      :opportunity-id="listenDialog.opportunityId" 
      @close-dialog="closeListenDialog" />

    <upload-dialog 
      :dialog-visible="uploadDialog.visible" 
      @close-dialog="closeUploadDialog" />
  </section>
</template>

<script>
import UploadDialog from '../../components/UploadDialog'
import FormDialog from './formDialog'
import FollowForm from './followForm'
import ListenDialog from './listenDialog'
import initData from '@/mixins/initData'
import { listAdvisorOperators } from '@/api/account'
import { closeCustomerRequest, reopenCustomerRequest, batchOpportunity, listFollowLog } from '@/api/customer'

import {
  mapGetters
} from 'vuex'

export default {
  name: 'List',
  components: { FormDialog, FollowForm, ListenDialog, UploadDialog },
  mixins: [initData],
  props: {
    // eslint-disable-next-line vue/require-default-prop
    type: String
  },
  data() {
    return {
      followStatus: [1, 2, 5, 6, 9],
      filter: {
        date: []
      },
      customer: {
        name: '',
        mobile: '',
        followStatus: '',
        showClose: false,
        notAssign: false,
        date: ''
      },
      followStatusArray: [],
      customerDialog: {
        title: '添加客户',
        visible: false,
        id: 0,
        type: 'add',
        isPrivate: '0'
      },
      followDialog: {
        visible: false,
        id: 0,
        customerName: '',
        opportunityId: 0
      },
      // 折叠面板显示
      activeNames: ['1'],
      activeName: 'followTab',
      followLogs: null,

      batchFollowOperatorId: null,
      operators: [],
      batchFollowVisible: false,
      batchFollowLoading: false,
      selections: [],
      listenDialog: {
        visible: false,
        listenId: null,
        opportunityId: null
      },
      uploadDialog: {
        visible: false
      },
      style: 130,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  mounted() {
    this.followStatusArray = this.$store.getters.followStatusArray
    this.customer.followStatus = this.followStatus.join(',')

    // 调整操作段的宽度
    if (this.type === 'public') {
      this.style = 100
    } else {
      this.style = 130
    }
  },
  created() {
    this.$nextTick(() => {
      this.init()
    })
    listAdvisorOperators().then(res => {
      this.operators = res.data
    })
  },
  methods: {
    ...mapGetters(['getGradeName']),
    beforeInit() {
      this.customer.followStatus = this.followStatus.join(',')
      if (this.filter.date != "" && this.filter.date != null) {
        this.customer.date = this.filter.date.join(',')
      }
      this.params = Object.assign(this.customer, {
        page: this.page,
        size: this.size
      })
      if (this.type === 'public') {
        this.url = 'merchant/customer/list'
      } else if (this.type === 'private') {
        this.url = 'merchant/opportunity/list'
      }
      return true
    },
    tableRowClassName({row, rowIndex}) {
      if (row.intention === 4) {
        return 'warning-row';
      } else if (row.intention === 3) {
        return 'success-row';
      }
      return '';
    },
    addCustomer(id) {
      console.log('打开客户ID为：' + id)
      if (id) {
        this.customerDialog.id = id
        this.customerDialog.title = '编辑客户'
        this.customerDialog.type = 'edit'
      } else {
        this.customerDialog.id = 0
        this.customerDialog.type = 'add'
        if (this.type === 'private') {
          this.customerDialog.isPrivate = '1'
        }
      }
      this.customerDialog.visible = true
    },
    selectionChange(selections) {
      this.selections = selections
    },
    followSuccess() {
      this.followDialog.visible = false
      this.init()
    },
    onMore(id) {
      this.$router.push({
        path: '/customer/detail/' + id 
      })
    },
    updateOpportunity(id, customerName, opportunityId) {
      this.followDialog.id = id
      this.followDialog.customerName = customerName
      this.followDialog.opportunityId = opportunityId
      this.followDialog.visible = true
      // 拉取跟进记录
      let params = {
        merchantCustomerId: id,
        pageNum: 1,
        pageSize: 2
      }
      listFollowLog(params).then(res => {
        this.followLogs = res.data.list
      })
    },
    batchFollow() {
      this.batchFollowVisible = true
    },
    batchFollowSubmit() {
      if (!this.batchFollowOperatorId) {
        this.$message.error('请选择一个课程顾问')
        return
      }
      this.batchFollowLoading = true
      const merchantCustomerIds = []
      this.selections.forEach(selection => {
        merchantCustomerIds.push(selection.merchantCustomerId)
      })
      batchOpportunity({
        merchantCustomerIds: merchantCustomerIds,
        operatorId: this.batchFollowOperatorId
      }).then(res => {
        this.$message.success('指派成功' + res.data + '条数据')
        this.init()
      }).finally(() => {
        this.batchFollowLoading = false
        this.batchFollowVisible = false
      })
    },
    closeCustomer(merchantCustomerId) {
      console.log('废弃客户：' + merchantCustomerId)
      this.$confirm('确认要废弃此客户资源吗？', '提示', {
        type: 'warning'
      }).then(() => {
        closeCustomerRequest(merchantCustomerId).then(() => {
          this.$message('已废弃此客户资源')
          this.init()
        })
      })
    },
    reopenCustomer(merchantCustomerId) {
      console.log('重新获取客户：' + merchantCustomerId)
      this.$confirm('确认要重新获取此客户吗？', '提示', {
        type: 'warning'
      }).then(() => {
        reopenCustomerRequest(merchantCustomerId).then(() => {
          this.$message('已获取此客户资源')
          this.init()
        })
      })
    },
    listenClass(row) {
      this.listenDialog.visible = true
      this.listenDialog.listenId = row.listenId
      this.listenDialog.opportunityId = row.opportunityId
    },
    closeListenDialog(isRefresh) {
      this.listenDialog.visible = false
      if (isRefresh) {
        this.init()
      }
    },
    closeUploadDialog(isRefresh) {
      this.uploadDialog.visible = false
      if (isRefresh) {
        this.init()
      }
    },
    closeFormDialog(isRefresh) {
      this.customerDialog.visible = false
      if (isRefresh) {
        this.init()
      }
    }
  }
}
</script>

<style scoped>
.el-checkbox.is-bordered.el-checkbox--small {
  padding: 7px 15px 7px 10px;
}
.follow-source {
  padding: 0 20px;
}
.more {
  width: 100%;
  padding: 15px;
}
</style>
